package com.sora.sora.message.controller;

import com.sora.sora.common.annotation.Auth;
import com.sora.sora.common.model.vo.ResultVO;
import com.sora.sora.common.utils.ResponseResult;
import com.sora.sora.message.service.MailService;
import com.sora.sora.security.login.JwtManager;
import com.sora.sora.security.login.model.bo.verify.CodeFactory;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Auth(id = 1000, name = "邮件测试")
@Api(value = "邮件发送模块", tags = "邮件发送模块")
@RestController
@RequestMapping("mail")
public class EmailController {

    @Resource
    MailService mailService;

    @Resource
    ResponseResult responseResult;

    @Resource
    CodeFactory codeFactory;

    @Resource
    JwtManager jwtManager;

    @Value("${spring.mail.username}")
    String sender;


    @ApiOperation(value = "更改密码前进行认证")
    @ApiImplicitParam(name = "uid", value = "用户id", required = true, paramType = "query", dataType = "Int")
    @GetMapping("/update_password")
    public ResultVO<String> updatePassword(@RequestParam("uid") Integer uid) {
        String code = codeFactory.getNumberCode().value();
        String title = "【Teio】您正在修改密码";
        String content = "如非本人操作，请尽快修改密码。您的验证码如下：" + code;
        int i = mailService.sendEmail(sender, uid, title, content);
        return i == 1 ? responseResult.ok(code) : responseResult.faile();
    }

    @ApiOperation(value = "产生token")
    @GetMapping("access_token")
    public ResultVO<String> generateToken(String username) {
        String accesskey = jwtManager.generateAccessToken(username);
        return responseResult.ok(accesskey);
    }

    @ApiOperation(value = "解析token")
    @GetMapping("/parse")
    public ResultVO parseToken(String token) {
        Claims claims = jwtManager.parserAccessToken(token);
        if (claims != null) {
            return responseResult.ok();
        }
        return responseResult.faile();
    }

}
